let baseUrl = "https://dazi.hckj88.net" // 生产环境
// let baseUrl = "http://dazi.wry8.cn" // 测试环境

// 将对象转换为查询字符串
const objectToQueryString = (obj) => {
	if (!obj || typeof obj !== "object") return ""

	const params = []
	for (const key in obj) {
		if (obj.hasOwnProperty(key) && obj[key] !== undefined && obj[key] !== null) {
			params.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
		}
	}
	return params.join("&")
}

// 构建完整的URL（处理GET请求参数）
const buildUrl = (baseUrl, path, method, data) => {
	let fullUrl = baseUrl + path
	if (method.toLowerCase() === "get" && data && Object.keys(data).length > 0) {
		const queryString = objectToQueryString(data)
		if (queryString) {
			// 检查URL是否已经包含问号
			const hasQuery = fullUrl.indexOf('?') !== -1
			fullUrl += (hasQuery ? '&' : '?') + queryString
		}
	}
	return fullUrl
}

// 不带token请求
const httpRequest = (opts, data) => {
	const fullUrl = buildUrl(baseUrl, opts.url, opts.method, opts.data)
	console.log(fullUrl, 'fullUrl');

	const httpDefaultOpts = {
		url: fullUrl,
		// GET请求不需要在body中传递data，已经拼接到URL中了
		data: opts.method.toLowerCase() === "get" ? {} : opts.data,
		method: opts.method,
		header: opts.method == "get" ? {
			"X-Requested-With": "XMLHttpRequest",
			Accept: "application/json",
			"Content-Type": "application/json; charset=UTF-8",
		} : {
			"X-Requested-With": "XMLHttpRequest",
			"Content-Type": "application/json; charset=UTF-8",
		},
		dataType: "json",
	}

	const promise = new Promise((resolve, reject) => {
		uni
			.request(httpDefaultOpts)
			.then((res) => {
				resolve(res[1])
			})
			.catch((response) => {
				reject(response)
			})
	})
	return promise
}

//带Token请求
const httpTokenRequest = (opts, data) => {
	const token = uni.getStorageSync("token")

	if (!token) {
		return handleAuthError();
	}

	// 构建完整URL
	const fullUrl = buildUrl(baseUrl, opts.url, opts.method, opts.data)

	const httpDefaultOpts = {
		url: fullUrl,
		data: opts.method.toLowerCase() === "get" ? {} : opts.data,
		method: opts.method,
		header: {
			token: token,
			"X-Requested-With": "XMLHttpRequest",
			"Content-Type": "application/json; charset=UTF-8",
		},
		dataType: opts.dataType || "json",
	}

	return new Promise((resolve, reject) => {
		uni.request(httpDefaultOpts)
			.then((res) => {
				const response = res[1];
				// 统一处理HTTP错误状态码
				if (!response || response.statusCode !== 200) {
					return reject(new Error(`网络错误: ${response?.statusCode || '未知错误'}`));
				}

				const data = response.data;
				// 处理业务逻辑错误
				if (data.code === 5000 || data.code === 401) {
					// token过期或未授权
					return handleAuthError(reject);
				} else if (data.code !== 1 && data.code !== 200 && data.code !== 0) {
					// 其他业务错误
					return reject(new Error(data.msg || '操作失败'));
				}

				resolve(response);
			})
			.catch((error) => {
				console.error('请求异常:', error);
				reject(error);
			});
	});
};

// 统一处理认证错误
function handleAuthError(reject) {
	uni.clearStorageSync();
	if (getApp().$store) {
		getApp().$store.commit('CLEAR_USER_DATA');
		getApp().$store.commit('SET_LOGIN_STATUS', false);
	}
	uni.showToast({
		title: "登录已过期，请重新登录",
		icon: "none",
		duration: 2000
	});
	setTimeout(() => {
		uni.reLaunch({
			url: '/pages/user/index'
		});
	}, 1500);
	return Promise.reject(new Error("认证失败"));
}

// 拦截器
const hadToken = () => {
	const token = uni.getStorageSync("token")

	if (token == "" || token == undefined || token == null) {
		uni.showToast({
			title: "账号已过期，请重新登录",
			icon: "none",
			complete: () => {
				uni.reLaunch({
					url: "/pages/user/index",
				})
			},
		})
		return false
	}
	return true
}

export default {
	baseUrl,
	httpRequest,
	httpTokenRequest,
	hadToken,
}